<template>
  <div class="phone">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="60px"
      class="demo-ruleForm"
      required
    >
      <el-form-item label="手机号" prop="phone" size="large">
        <el-input v-model="ruleForm.phone" />
      </el-form-item>
      <el-form-item label="验证码" prop="yzm" size="large">
        <div class="verify-code">
          <el-input v-model="ruleForm.yzm" />
          <el-button class="get-btn" type="primary">获取验证码</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { reactive } from 'vue';
import type { FormInstance } from 'element-plus';

export default defineComponent({
  setup() {
    // const ruleFormRef = ref<FormInstance>();
    const ruleForm = reactive({
      phone: '',
      yzm: ''
    });

    const validateYzm = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      } else {
        if (ruleForm.yzm !== '123') {
          callback(new Error('验证码错误'));
        }
        callback();
      }
    };
    const validatePhone = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else {
        if (!rule.pattern.test(ruleForm.phone)) {
          callback(new Error('手机号码格式不对'));
        }
        callback();
      }
    };

    const rules = reactive({
      phone: [
        {
          pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
          validator: validatePhone,
          trigger: 'blur'
        }
      ],
      yzm: [
        {
          validator: validateYzm,
          trigger: 'blur'
        }
      ]
    });

    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          console.log('submit!');
        } else {
          console.log('error submit!');
          return false;
        }
      });
    };
    return {
      ruleForm,
      rules,
      submitForm
    };
  }
});
</script>

<style lang="scss" scoped>
.verify-code {
  display: flex;

  .get-btn {
    margin-left: 8px;
  }
}
</style>
